#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#define N 15
void sys_err(char* str){
	perror(str);
}

void inverseArray(int* retArray,int numsSize){
	for (int i = 0 ; i < numsSize/2 ; i++){
		int tmp=retArray[numsSize-1-i];
		retArray[numsSize-1-i]=retArray[i];
		retArray[i]=tmp;
	}
}

int* sortedSquares(int* nums, int numsSize, int* returnSize){
	int* retArray = (int* )malloc(sizeof(int)*numsSize);
	int numNegtive=0,i,j,index=0;
	*returnSize =numsSize;

	for (int i = 0; i < numsSize ; i++ ){
		if (nums[i]<0){
			numNegtive++;
		}
		retArray[i] = nums[i]*nums[i];
	}

	if (numNegtive == 0){//全为正数
		return retArray;
 	} else if (numNegtive == numsSize){//全为负数
		inverseArray(retArray,numsSize);
		return retArray;
	} else {//有负有正
		int* newArray = (int* )malloc(sizeof(int)*numsSize);
		for( i = 0 ; nums[i] < 0 ; i++);//寻找正负数分界点
		for( j = i-1 ; i < numsSize || j >= 0 ; index ++){//只要有i，j有一个合法，那么就表示一边的数字没有遍历完成。i最大的合法下标是numsSize-1,j是0
			if (j < 0){//j遍历完成
				newArray[index] = retArray[i++];
			} else if ( i >= numsSize){//i遍历完成
				newArray[index] = retArray[j--];
			} else if ( j >= 0 && i < numsSize){
				newArray[index] = retArray[i] <= retArray[j]? retArray[i++] : retArray[j--];
			}
		} return newArray;
	}
	return 0;
}

int main(int argc,char* argv[]){
	int arr[N] = {-100,-98,-10,-9,-8,-1,0,1,3,5,7,10,13,18,100},returnSize;int* pretArray;
	int numsSize = sizeof(arr)/sizeof(int);
	returnSize = numsSize;
	pretArray = sortedSquares(arr,numsSize,&returnSize);
	for (int i = 0;i<returnSize;i++)
		printf("%d ",pretArray[i]);
}
